<template>
  <div class="medicines-layout">
    <!-- 左侧导航区 -->
    <aside class="sidebar-nav">
      <el-menu :default-active="activeTab" class="el-menu-vertical-demo">
        <el-menu-item index="medicines" @click="activeTab = 'medicines'">
          全部药品
        </el-menu-item>
        <el-menu-item index="orders" @click="activeTab = 'orders'">
          我的订单
        </el-menu-item>
      </el-menu>
    </aside>
    <!-- 主内容区 -->
    <div class="medicines-page">
      <!-- 全部药品 -->
      <template v-if="activeTab === 'medicines'">
        <div class="page-header">
          <h1>药品商城</h1>
          <div class="search-bar">
            <el-input
              v-model="searchQuery"
              placeholder="搜索药品名称、类别或描述"
              prefix-icon="el-icon-search"
              clearable
              @input="handleSearch"
            />
          </div>
        </div>
        <!-- 筛选和排序区域 -->
        <div class="filters-section">
          <div class="category-filters">
            <el-radio-group v-model="selectedCategory" @change="handleCategoryChange">
              <el-radio-button label="">全部</el-radio-button>
              <el-radio-button v-for="category in categories" :key="category" :label="category">
                {{ category }}
              </el-radio-button>
            </el-radio-group>
          </div>
          <div class="sort-options">
            <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
              <el-option label="默认排序" value="default" />
              <el-option label="价格从低到高" value="priceAsc" />
              <el-option label="价格从高到低" value="priceDesc" />
              <el-option label="销量优先" value="sales" />
            </el-select>
          </div>
        </div>
        <!-- 药品列表 -->
        <div class="medicines-grid" v-loading="loading">
          <el-card v-for="medicine in displayMedicines" :key="medicine.id" class="medicine-card">
            <div class="medicine-image">
              <img :src="medicine.image" :alt="medicine.name" />
            </div>
            <div class="medicine-info">
              <h3 class="medicine-name">{{ medicine.name }}</h3>
              <div class="medicine-category">{{ medicine.category }}</div>
              <div class="medicine-price">¥{{ medicine.price.toFixed(2) }}</div>
              <div class="medicine-description">{{ medicine.description }}</div>
              <div class="medicine-stock">库存: {{ medicine.stock }}件</div>
              <div class="medicine-actions">
                <el-button type="primary" @click="showMedicineDetail(medicine)">查看详情</el-button>
                <el-button type="success" @click="addToCart(medicine)" :disabled="medicine.stock <= 0">
                  加入购物车
                </el-button>
                <el-button :type="isFavorited(medicine) ? 'warning' : 'info'" @click="toggleFavorite(medicine)" circle>
                  <el-icon>
                    <component :is="isFavorited(medicine) ? StarFilled : Star" />
                  </el-icon>
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
        <!-- 分页器 -->
        <div class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalMedicines"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
          />
        </div>
        <!-- 药品详情对话框 -->
        <el-dialog
          :title="selectedMedicine ? selectedMedicine.name : ''"
          v-model="dialogVisible"
          width="50%"
        >
          <div v-if="selectedMedicine" class="medicine-detail">
            <div class="detail-image">
              <img :src="selectedMedicine.image" :alt="selectedMedicine.name" />
            </div>
            <div class="detail-info">
              <h2>{{ selectedMedicine.name }}</h2>
              <p class="detail-category">类别：{{ selectedMedicine.category }}</p>
              <p class="detail-price">价格：¥{{ selectedMedicine.price.toFixed(2) }}</p>
              <p class="detail-stock">库存：{{ selectedMedicine.stock }}件</p>
              <p class="detail-manufacturer">生产厂家：{{ selectedMedicine.manufacturer }}</p>
              <p class="detail-specification">规格：{{ selectedMedicine.specification }}</p>
              <p class="detail-usage">用法用量：{{ selectedMedicine.usage }}</p>
              <div class="detail-description">
                <h3>产品说明：</h3>
                <p>{{ selectedMedicine.description }}</p>
              </div>
              <div class="detail-actions">
                <el-input-number
                  v-model="purchaseQuantity"
                  :min="1"
                  :max="selectedMedicine.stock"
                  size="small"
                />
                <el-button type="primary" @click="addToCart(selectedMedicine, purchaseQuantity)">
                  加入购物车
                </el-button>
                <el-button :type="isFavorited(selectedMedicine) ? 'warning' : 'info'" @click="toggleFavorite(selectedMedicine)" circle>
                  <el-icon>
                    <component :is="isFavorited(selectedMedicine) ? StarFilled : Star" />
                  </el-icon>
                  {{ isFavorited(selectedMedicine) ? '已收藏' : '收藏' }}
                </el-button>
              </div>
            </div>
          </div>
        </el-dialog>
      </template>
      <!-- 我的订单 -->
      <template v-else-if="activeTab === 'orders'">
        <div class="orders-page">
          <div class="page-header">
            <h1>我的订单</h1>
          </div>
          <!-- 搜索和筛选 -->
          <div class="filter-section">
            <el-input
              v-model="orderSearchQuery"
              placeholder="搜索订单号或商品名称"
              prefix-icon="el-icon-search"
              clearable
              class="search-input"
              @input="handleOrderSearch"
            />
            <el-radio-group v-model="statusFilter" @change="handleStatusChange">
              <el-radio-button label="">全部</el-radio-button>
              <el-radio-button label="pending">待付款</el-radio-button>
              <el-radio-button label="paid">待发货</el-radio-button>
              <el-radio-button label="shipped">待收货</el-radio-button>
              <el-radio-button label="completed">已完成</el-radio-button>
              <el-radio-button label="cancelled">已取消</el-radio-button>
            </el-radio-group>
          </div>
          <!-- 订单列表 -->
          <div class="orders-list" v-loading="ordersLoading">
            <el-empty
              v-if="!filteredOrders.length"
              :description="ordersEmptyText"
            >
              <el-button type="primary" @click="activeTab = 'medicines'">
                去购物
              </el-button>
            </el-empty>
            <el-card v-for="order in pagedOrders" :key="order.id" class="order-card">
              <div class="order-header">
                <div class="order-info">
                  <span class="order-id">订单号：{{ order.id }}</span>
                  <span class="order-time">下单时间：{{ formatDate(order.createTime) }}</span>
                </div>
                <div class="order-status" :class="order.status">
                  {{ getStatusText(order.status) }}
                </div>
              </div>
              <div class="order-items">
                <div v-for="item in order.items" :key="item.id" class="order-item">
                  <img :src="item.image" :alt="item.name" class="item-image">
                  <div class="item-info">
                    <div class="item-name">{{ item.name }}</div>
                    <div class="item-price">¥{{ (item.price ?? 0).toFixed(2) }} × {{ item.quantity }}</div>
                  </div>
                </div>
              </div>
              <div class="order-footer">
                <div class="order-address">
                  <i class="el-icon-location"></i>
                  收货人：{{ order.shippingAddress.name }}
                  {{ order.shippingAddress.phone }}
                  {{ order.shippingAddress.address }}
                </div>
                <div class="order-total">
                  <span>共 {{ getTotalItems(order) }} 件商品</span>
                  <span class="total-amount">
                    实付款：<span class="amount">¥{{ (order.totalAmount ?? order.total ?? 0).toFixed(2) }}</span>
                  </span>
                </div>
                <div class="order-actions">
                  <el-button
                    v-if="order.status === 'pending'"
                    type="primary"
                    @click="continuePay(order)"
                  >继续支付</el-button>
                  <el-button
                    v-if="order.status === 'shipped'"
                    type="success"
                    @click="confirmReceive(order)"
                  >确认收货</el-button>
                  <el-button
                    v-if="order.status === 'completed' && !order.isReviewed"
                    type="primary"
                    plain
                    @click="writeReview(order)"
                  >评价</el-button>
                  <el-button
                    v-if="order.status === 'pending'"
                    type="danger"
                    plain
                    @click="cancelOrder(order)"
                  >取消订单</el-button>
                  <el-button
                    v-if="['completed', 'cancelled'].includes(order.status)"
                    type="danger"
                    plain
                    @click="deleteOrder(order)"
                  >删除订单</el-button>
                  <el-button
                    type="info"
                    plain
                    @click="showOrderDetail(order)"
                  >订单详情</el-button>
                </div>
              </div>
            </el-card>
            <!-- 分页器 -->
            <div class="pagination-container" v-if="filteredOrders.length">
              <el-pagination
                background
                layout="prev, pager, next"
                :total="filteredOrders.length"
                :page-size="ordersPageSize"
                :current-page="ordersCurrentPage"
                @current-change="handleOrdersPageChange"
              />
            </div>
          </div>
          <!-- 订单详情对话框 -->
          <el-dialog
            title="订单详情"
            v-model="detailDialogVisible"
            width="700px"
          >
            <div v-if="selectedOrder" class="order-detail">
              <div class="detail-section">
                <h3>订单信息</h3>
                <div class="detail-item">
                  <span class="label">订单编号：</span>
                  <span>{{ selectedOrder.id }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">创建时间：</span>
                  <span>{{ formatDate(selectedOrder.createTime) }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">订单状态：</span>
                  <span :class="selectedOrder.status">{{ getStatusText(selectedOrder.status) }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">支付方式：</span>
                  <span>{{ selectedOrder.paymentMethod === 'alipay' ? '支付宝' : '微信支付' }}</span>
                </div>
              </div>
              <div class="detail-section">
                <h3>收货信息</h3>
                <div class="detail-item">
                  <span class="label">收货人：</span>
                  <span>{{ selectedOrder.shippingAddress.name }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">联系电话：</span>
                  <span>{{ selectedOrder.shippingAddress.phone }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">收货地址：</span>
                  <span>{{ selectedOrder.shippingAddress.address }}</span>
                </div>
              </div>
              <div class="detail-section">
                <h3>商品信息</h3>
                <el-table :data="selectedOrder.items" style="width: 100%">
                  <el-table-column prop="name" label="商品名称">
                    <template #default="scope">
                      <div class="product-info">
                        <img :src="scope.row.image" :alt="scope.row.name" class="product-image">
                        <span>{{ scope.row.name }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="price" label="单价" width="100">
                    <template #default="scope">
                      ¥{{ (scope.row.price ?? 0).toFixed(2) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="quantity" label="数量" width="80" />
                  <el-table-column label="小计" width="120">
                    <template #default="scope">
                      ¥{{ ((scope.row.price ?? 0) * (scope.row.quantity ?? 0)).toFixed(2) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="detail-section">
                <h3>订单备注</h3>
                <div class="detail-item">
                  {{ selectedOrder.remark || '无' }}
                </div>
              </div>
              <div class="detail-footer">
                <div class="price-info">
                  <div class="price-item">
                    <span>商品总额：</span>
                    <span>¥{{ getSubtotal(selectedOrder).toFixed(2) }}</span>
                  </div>
                  <div class="price-item">
                    <span>运费：</span>
                    <span>¥{{ getShippingFee(selectedOrder).toFixed(2) }}</span>
                  </div>
                  <div class="price-item total">
                    <span>实付款：</span>
                    <span>¥{{ (selectedOrder.totalAmount ?? selectedOrder.total ?? 0).toFixed(2) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-dialog>
          <!-- 评价对话框 -->
          <el-dialog
            title="商品评价"
            v-model="reviewDialogVisible"
            width="500px"
          >
            <div v-if="selectedOrder" class="review-form">
              <div v-for="item in selectedOrder.items" :key="item.id" class="review-item">
                <div class="product-info">
                  <img :src="item.image" :alt="item.name" class="product-image">
                  <span>{{ item.name }}</span>
                </div>
                <div class="review-content">
                  <el-rate v-model="item.rating" :colors="rateColors" />
                  <el-input
                    v-model="item.review"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入您的评价"
                    maxlength="200"
                    show-word-limit
                  />
                </div>
              </div>
            </div>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="reviewDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitReview">提交评价</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { StarFilled, Star } from '@element-plus/icons-vue'

export default {
  name: 'Medicines',
  setup() {
    // 数据
    const medicines = ref([])
    const loading = ref(true)
    const searchQuery = ref('')
    const selectedCategory = ref('')
    const sortBy = ref('default')
    const currentPage = ref(1)
    const pageSize = ref(12)
    const dialogVisible = ref(false)
    const selectedMedicine = ref(null)
    const purchaseQuantity = ref(1)
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const activeTab = ref('medicines')
    // 订单区数据
    const orders = ref([])
    const ordersLoading = ref(false)
    const orderSearchQuery = ref('')
    const statusFilter = ref('')
    const ordersCurrentPage = ref(1)
    const ordersPageSize = ref(5)
    const detailDialogVisible = ref(false)
    const reviewDialogVisible = ref(false)
    const selectedOrder = ref(null)
    const rateColors = ['#99A9BF', '#F7BA2A', '#FF9900']
    // 收藏相关
    const user = computed(() => store.state.user || { id: '' })
    const isAuthenticated = computed(() => store.state.isAuthenticated)
    const favorites = ref([])

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 获取订单状态文本
    const getStatusText = (status) => {
      const statusMap = {
        pending: '待付款',
        paid: '待发货',
        shipped: '待收货',
        completed: '已完成',
        cancelled: '已取消'
      }
      return statusMap[status] || status
    }

    // 获取订单总商品数
    const getTotalItems = (order) => {
      return order.items?.reduce((total, item) => total + (item.quantity || 0), 0) || 0
    }

    // 获取订单小计
    const getSubtotal = (order) => {
      return order.items?.reduce((total, item) => total + (item.price || 0) * (item.quantity || 0), 0) || 0
    }

    // 获取运费
    const getShippingFee = (order) => {
      return order.shipping || 0
    }

    // 获取所有药品
    const fetchMedicines = async () => {
      try {
        loading.value = true
        const response = await axios.get('http://localhost:3000/medicines')
        medicines.value = response.data
      } catch (error) {
        ElMessage.error('获取药品列表失败')
        console.error('Error fetching medicines:', error)
      } finally {
        loading.value = false
      }
    }

    // 获取用户订单
    const fetchOrders = async () => {
      try {
        ordersLoading.value = true
        const userId = store.state.user?.id
        if (!userId) {
          ElMessage.warning('请先登录')
          return
        }
        const response = await axios.get(`http://localhost:3000/orders?userId=${userId}`)
        orders.value = response.data
      } catch (error) {
        ElMessage.error('获取订单列表失败')
        console.error('Error fetching orders:', error)
      } finally {
        ordersLoading.value = false
      }
    }

    // 计算属性
    const categories = computed(() => {
      const categorySet = new Set(medicines.value.map(m => m.category))
      return Array.from(categorySet)
    })

    const filteredMedicines = computed(() => {
      let result = [...medicines.value]

      // 应用搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(medicine => 
          medicine.name.toLowerCase().includes(query) ||
          medicine.category.toLowerCase().includes(query) ||
          medicine.description.toLowerCase().includes(query)
        )
      }

      // 应用分类过滤
      if (selectedCategory.value) {
        result = result.filter(medicine => medicine.category === selectedCategory.value)
      }

      // 应用排序
      switch (sortBy.value) {
        case 'priceAsc':
          result.sort((a, b) => a.price - b.price)
          break
        case 'priceDesc':
          result.sort((a, b) => b.price - a.price)
          break
        case 'sales':
          // 这里可以根据实际销量数据排序
          break
        default:
          // 默认排序，可以按照ID排序
          result.sort((a, b) => a.id - b.id)
      }

      return result
    })

    const totalMedicines = computed(() => filteredMedicines.value.length)

    const displayMedicines = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredMedicines.value.slice(start, end)
    })

    // 方法
    const handleSearch = () => {
      currentPage.value = 1
    }

    const handleCategoryChange = () => {
      currentPage.value = 1
    }

    const handleSort = () => {
      currentPage.value = 1
    }

    const handlePageChange = (page) => {
      currentPage.value = page
    }

    const showMedicineDetail = (medicine) => {
      selectedMedicine.value = medicine
      purchaseQuantity.value = 1
      dialogVisible.value = true
    }

    const addToCart = (medicine, quantity = 1) => {
      // 检查用户是否已登录
      if (!store.state.isAuthenticated) {
        ElMessage.warning('请先登录后再添加商品到购物车')
        router.push('/login')
        return
      }

      // 这里添加购物车逻辑
      const cartItem = {
        id: medicine.id,
        name: medicine.name,
        price: medicine.price,
        quantity: quantity,
        image: medicine.image
      }
      
      // 使用 Vuex mutation 来添加购物车
      store.commit('ADD_TO_CART', cartItem)
      
      ElMessage.success('已添加到购物车')
      dialogVisible.value = false
    }

    // 新增跳转方法
    const goToMedicines = () => {
      router.push('/medicines')
    }
    const goToOrders = () => {
      router.push('/orders')
    }

    // 生命周期钩子
    onMounted(() => {
      fetchMedicines()
      loadFavorites()
      // 根据路由参数自动切换tab
      if (route.query.tab === 'orders') {
        activeTab.value = 'orders'
        fetchOrders() // 切换到订单tab时获取订单数据
      }
    })

    // 监听路由变化，支持前进/后退时tab切换
    watch(() => route.query.tab, (newTab) => {
      if (newTab === 'orders') {
        activeTab.value = 'orders'
        fetchOrders() // 切换到订单tab时获取订单数据
      } else if (newTab === 'medicines') {
        activeTab.value = 'medicines'
      }
    })

    // 监听activeTab变化
    watch(activeTab, (newTab) => {
      if (newTab === 'orders') {
        fetchOrders() // 切换到订单tab时获取订单数据
      }
    })

    // 订单相关计算属性和方法
    const filteredOrders = computed(() => {
      let result = Array.isArray(orders.value) ? [...orders.value] : [];
      // 搜索过滤
      if (orderSearchQuery.value) {
        const query = orderSearchQuery.value.toLowerCase();
        result = result.filter(order =>
          String(order.id).toLowerCase().includes(query) ||
          (order.items && order.items.some(item => item.name && item.name.toLowerCase().includes(query)))
        );
      }
      // 状态过滤
      if (statusFilter.value) {
        result = result.filter(order => order.status === statusFilter.value);
      }
      return result;
    });
    const pagedOrders = computed(() => {
      const start = (ordersCurrentPage.value - 1) * ordersPageSize.value;
      const end = start + ordersPageSize.value;
      return filteredOrders.value.slice(start, end);
    });
    const ordersEmptyText = computed(() => {
      if (orderSearchQuery.value || statusFilter.value) {
        return '没有找到相关订单';
      }
      return '暂无订单';
    });
    // 订单分页、搜索等方法
    const handleOrdersPageChange = (page) => {
      ordersCurrentPage.value = page;
    };
    const handleOrderSearch = () => {
      ordersCurrentPage.value = 1;
    };

    const deleteOrder = async (order) => {
      try {
        await ElMessageBox.confirm('确定要删除该订单吗？删除后无法恢复。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        await axios.delete(`http://localhost:3000/orders/${order.id}`);
        ElMessage.success('订单已删除');
        fetchOrders(); // 重新获取订单列表
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除订单失败');
          console.error('Error deleting order:', error);
        }
      }
    };

    const cancelOrder = async (order) => {
      try {
        await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        // 只需要 PATCH status 字段
        await axios.patch(`http://localhost:3000/orders/${order.id}`, { status: 'cancelled' });
        ElMessage.success('订单已取消');
        fetchOrders(); // 重新获取订单列表
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('取消订单失败');
          console.error('Error cancelling order:', error);
        }
      }
    };

    // 加载收藏列表
    const loadFavorites = async () => {
      if (!user.value.id) return
      try {
        const res = await axios.get(`http://localhost:3000/users/${user.value.id}`)
        favorites.value = res.data.favorites || []
      } catch (e) {
        favorites.value = []
      }
    }

    // 判断商品是否已收藏
    const isFavorited = (medicine) => {
      return favorites.value.some(item => item.id === medicine.id)
    }

    // 收藏/取消收藏
    const toggleFavorite = async (medicine) => {
      if (!isAuthenticated.value) {
        ElMessage.warning('请先登录后再收藏商品')
        router.push('/login')
        return
      }
      let newFavorites
      if (isFavorited(medicine)) {
        // 取消收藏
        newFavorites = favorites.value.filter(item => item.id !== medicine.id)
      } else {
        // 添加收藏
        newFavorites = [...favorites.value, medicine]
      }
      try {
        await axios.patch(`http://localhost:3000/users/${user.value.id}`, { favorites: newFavorites })
        favorites.value = newFavorites
      } catch (e) {
        // 移除ElMessage.error
      }
    }

    // 监听user变化
    watch(() => store.state.user, () => {
      loadFavorites()
    })

    return {
      medicines,
      loading,
      searchQuery,
      selectedCategory,
      sortBy,
      currentPage,
      pageSize,
      dialogVisible,
      selectedMedicine,
      purchaseQuantity,
      categories,
      totalMedicines,
      displayMedicines,
      handleSearch,
      handleCategoryChange,
      handleSort,
      handlePageChange,
      showMedicineDetail,
      addToCart,
      goToMedicines,
      goToOrders,
      activeTab,
      orders,
      ordersLoading,
      orderSearchQuery,
      statusFilter,
      ordersCurrentPage,
      ordersPageSize,
      detailDialogVisible,
      reviewDialogVisible,
      selectedOrder,
      rateColors,
      filteredOrders,
      pagedOrders,
      ordersEmptyText,
      handleOrdersPageChange,
      handleOrderSearch,
      fetchOrders,
      formatDate,
      getStatusText,
      getTotalItems,
      getSubtotal,
      getShippingFee,
      deleteOrder,
      cancelOrder,
      favorites,
      isFavorited,
      toggleFavorite,
      StarFilled,
      Star,
    }
  }
}
</script>

<style scoped>
.medicines-layout {
  display: flex;
  align-items: flex-start;
}
.sidebar-nav {
  width: 180px;
  min-height: 600px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  margin-right: 32px;
  padding: 24px 0 0 0;
}
.medicines-page {
  flex: 1;
  padding: 20px;
  max-width: 1200px;
  margin: 0;
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  color: #2c3e50;
  margin-bottom: 20px;
}

.search-bar {
  max-width: 500px;
  margin-bottom: 20px;
}

.search-bar .el-input__inner {
  transition: all 0.3s ease;
}

.search-bar .el-input__inner:focus {
  transform: scale(1.02);
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.filters-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 20px;
}

.category-filters {
  flex-grow: 1;
}

.medicines-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.medicine-card {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  top: 0;
}

.medicine-card:hover {
  transform: translateY(-8px) scale(1.02);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.1);
}

.medicine-image {
  height: 200px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}

.medicine-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
  transition: all 0.5s ease;
}

.medicine-card:hover .medicine-image img {
  transform: scale(1.1);
}

.medicine-info {
  padding: 15px;
}

.medicine-name {
  font-size: 18px;
  color: #2c3e50;
  margin: 0 0 10px;
}

.medicine-category {
  color: #909399;
  font-size: 14px;
  margin-bottom: 10px;
}

.medicine-price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
  transition: all 0.3s ease;
}

.medicine-card:hover .medicine-price {
  transform: scale(1.1);
  color: #e4393c;
}

.medicine-description {
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.medicine-stock {
  color: #909399;
  font-size: 14px;
  margin-bottom: 15px;
}

.medicine-actions {
  display: flex;
  gap: 10px;
}

.medicine-actions .el-button {
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.medicine-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.medicine-actions .el-button::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.6s ease, height 0.6s ease;
}

.medicine-actions .el-button:active::after {
  width: 200px;
  height: 200px;
  opacity: 0;
}

.pagination-container {
  text-align: center;
  margin-top: 20px;
}

/* 详情对话框样式 */
.medicine-detail {
  display: flex;
  gap: 30px;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.detail-image {
  flex: 0 0 300px;
}

.detail-image img {
  width: 100%;
  height: auto;
  border-radius: 8px;
}

.detail-info {
  flex: 1;
}

.detail-info h2 {
  margin: 0 0 20px;
  color: #2c3e50;
}

.detail-category,
.detail-price,
.detail-stock,
.detail-manufacturer,
.detail-specification,
.detail-usage {
  margin-bottom: 10px;
  color: #606266;
}

.detail-price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.detail-description {
  margin-top: 20px;
}

.detail-description h3 {
  margin-bottom: 10px;
  color: #2c3e50;
}

.detail-actions {
  margin-top: 30px;
  display: flex;
  gap: 20px;
  align-items: center;
}

/* 分类按钮动画 */
.category-filters .el-radio-button__inner {
  transition: all 0.3s ease;
}

.category-filters .el-radio-button__inner:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式布局 */
@media (max-width: 768px) {
  .medicines-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }

  .medicine-card:hover {
    transform: translateY(-4px) scale(1.01);
  }
  
  .medicine-actions .el-button:hover {
    transform: translateY(-1px);
  }

  .medicine-detail {
    flex-direction: column;
  }

  .detail-image {
    flex: none;
    margin-bottom: 20px;
  }
}

/* 加载动画 */
.medicines-grid[v-loading] {
  position: relative;
}

.medicines-grid[v-loading]::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  z-index: 1;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    background: rgba(255, 255, 255, 0.8);
  }
  50% {
    background: rgba(255, 255, 255, 0.95);
  }
  100% {
    background: rgba(255, 255, 255, 0.8);
  }
}

/* 分页器动画 */
.el-pagination .el-pager li {
  transition: all 0.3s ease;
}

.el-pagination .el-pager li:hover {
  transform: scale(1.1);
}

/* 订单区样式 */
.orders-page { padding: 0; max-width: 100%; margin: 0; animation: none; }

/* 订单列表样式 */
.orders-list {
  margin-top: 20px;
}

.order-card {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.order-info {
  display: flex;
  gap: 20px;
}

.order-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.order-status.pending { color: #e6a23c; }
.order-status.paid { color: #409eff; }
.order-status.shipped { color: #67c23a; }
.order-status.completed { color: #909399; }
.order-status.cancelled { color: #f56c6c; }

.order-items {
  padding: 15px;
}

.order-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
}

.item-price {
  font-size: 13px;
  color: #909399;
}

.order-footer {
  padding: 15px;
  background-color: #f8f8f8;
  border-top: 1px solid #ebeef5;
}

.order-address {
  font-size: 13px;
  color: #606266;
  margin-bottom: 10px;
}

.order-total {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
  font-size: 13px;
  color: #606266;
}

.total-amount {
  font-size: 16px;
  color: #f56c6c;
}

.total-amount .amount {
  font-weight: bold;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

/* 订单详情样式 */
.order-detail {
  padding: 20px;
}

.detail-section {
  margin-bottom: 30px;
}

.detail-section h3 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.detail-item .label {
  width: 100px;
  color: #909399;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.detail-footer {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.price-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10px;
}

.price-item {
  font-size: 14px;
  color: #606266;
}

.price-item.total {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

/* 评价表单样式 */
.review-form {
  padding: 20px;
}

.review-item {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.review-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.review-content {
  margin-top: 10px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .order-info {
    flex-direction: column;
    gap: 5px;
  }

  .order-total {
    flex-direction: column;
    align-items: flex-end;
    gap: 5px;
  }

  .order-actions {
    flex-wrap: wrap;
  }
}
</style> 